package com.amigo.online.message.interceptor;

import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.core.security.IgnoreSecurity;
import com.amigo.online.common.util.StringUtils;
import com.amigo.online.message.exception.TokenException;
import com.amigo.online.message.service.TokenManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * token拦截器
 *
 * @author amigo
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static  TokenInterceptor tokenInterceptor = new TokenInterceptor();
    public static TokenInterceptor getTokenInterceptor() {
        return tokenInterceptor;
    }

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private TokenManagerService tokenManagerService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        LocalUser.removeUser();
        super.afterCompletion(request, response, handler, ex);
        // logger.info("请求结束!请求线程名:" + Thread.currentThread().getId() + ",请求路径:" +
        // request.getRequestURI());
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();


        String token = request.getHeader("ACCESS_TOKEN");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("access_token");
        }
        logger.info("Token:{},请求路径{}", token, request.getRequestURI());
        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            if (StringUtils.isNotEmpty(token)) {
                tokenManagerService.checkToken(token);
            }
            return true;
        }
        if (StringUtils.isEmpty(token)) {
            logger.info("token为空,Token:{},请求路径{}", token, request.getRequestURI());
            throw new TokenException(StatusCode.UNAUTHORIZED);
        }
        // 检查 token 有效性
        if (!tokenManagerService.checkToken(token)) {
            logger.error("Token:{},请求路径{},checkToken返回false", token, request.getRequestURI());
            throw new TokenException(StatusCode.UNAUTHORIZED);
        }

        return true;
    }

}
